package com.itheima.service.Impl;

import com.itheima.VO.OrderDataVO;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingVO;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Component
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 获取预约订单的数据
     * @return
     */
    public void exportordersetting(String filename,HttpServletResponse response) {


        try {
            //基于模板文件创建一个新的Excel文件
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");
            // 设置响应头和客户端保存文件名
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename+".xlsx", "UTF-8"));
            XSSFWorkbook excel=new XSSFWorkbook(is);
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("预约设置模板");


            List<OrderSetting> ordersetting = orderSettingMapper.getOrderSetting();


            for (int i = 0; i <24; i++) {
                XSSFRow row=sheet.getRow(1+i);
                if (row == null) {
                    row=sheet.createRow(1+i);
                }
                Date orderDate = ordersetting.get(i).getDate();
                int number = ordersetting.get(i).getNumber();
                row.createCell(0).setCellValue(orderDate+"");
                row.createCell(1).setCellValue(number+"");

            }


            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            excel.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {

        return orderSettingMapper.getordersettingByMonth(month);
    }

    /**
     * 根据日期修改可预约人数
     * @param date
     */
    public void editnumberByOrderDate(OrderDataVO date) {
        orderSettingMapper.updateNumberByOrderDate(date);
    }


}
